package malfunction_service

import (
	"repairs/models"
)

type Malfunction struct {
	ID          int
	UserID      int
	Room        string
	State       int
	Position    string
	Type        int
	Description string

	PageNum  int
	PageSize int
}

func (m *Malfunction) Add() error {
	mal := map[string]interface{}{
		"user_id":     m.UserID,
		"room":        m.Room,
		"type":        m.Type,
		"state":       m.State,
		"position":    m.Position,
		"description": m.Description,
	}
	err := models.AddMalfunction(mal)
	return err
}

func (m *Malfunction) ExistByID() (bool, error) {
	return models.ExistMalfunctionById(m.ID)
}

func (m *Malfunction) UpdateState() error {
	return models.UpdateMalfunctionState(m.ID, m.State)
}

func (m *Malfunction) GetAll() ([]*models.Malfunction, error) {
	malfunctions, err := models.GetMalfunctions(m.PageNum, m.PageSize, m.getMaps())
	if err != nil {
		malfunctions = nil
	}
	return malfunctions, err
}

func (m *Malfunction) Delete() error {
	return models.DeleteMalfunction(m.ID)
}

func (m *Malfunction) Count() (int, error) {
	return models.GetMalfunctionTotal(m.getMaps())
}

func (m *Malfunction) getMaps() map[string]interface{} {
	maps := make(map[string]interface{})
	maps["deleted_on"] = 0
	if m.UserID != 0 {
		maps["user_id"] = m.UserID
	}
	if m.Room != "" {
		maps["room"] = m.Room
	}
	if m.State != 0 {
		maps["state"] = m.State
	}
	if m.Type != 0 {
		maps["type"] = m.Type
	}
	return maps
}
